package com.wangyk.thymeleafproject.resttemplate;

import com.netflix.discovery.converters.Auto;
import com.wangyk.rabbitmqcommon.model.console.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 使用RestTemplate调用
 * */
@Controller
@RequestMapping("/rest")
public class RestTemplateController
{
    //2.第二种方式，使用LoadBalancerClient获取服务名
    @Resource
    private LoadBalancerClient loadBalancerClient;

    //3.第三种方式，使用注解
    @Autowired
    private RestTemplate restTemplate3;

    @RequestMapping("/test.do")
    @ResponseBody
    public User testMethod()
    {
        //1.第一种方式，直接使用地址
        RestTemplate restTemplate = new RestTemplate();
        User user = restTemplate.getForObject(
            "http://localhost:8092/rabbitmq/userpro/select_by_user_id.do?userId=1",
            User.class);
        //2.第二种方式，拼接地址，使用loadBalancerClient获取服务名
        ServiceInstance choose = loadBalancerClient.choose("SPIRNG-BOOT-RABBITMQ");
        String host = choose.getHost();
        int port = choose.getPort();
        String url = "http://" + host + ":" + port + "/rabbitmq/userpro/select_by_user_id.do?userId=2";
        RestTemplate restTemplate2 = new RestTemplate();
        User user2 = restTemplate2.getForObject(
            url,
            User.class);
        //3.第三种方式，使用LoadBalance注解，使用服务名即可
        User user3 = restTemplate3.getForObject(
            "http://" + "CONSOLE" + "/console/userpro/select_by_user_id.do?userId=3", User.class);
        return user3;
    }
}
